package falcon.script;

import java.util.ArrayList;

import falcon.common.Errno;

public final class FalconLangCompiler {
	
	public FalconLangCompiler() {
		m_tokenList = new ArrayList<FalconLangToken>(256);
		m_astList = new ArrayList<FalconLangAst>(128);
		m_instructionList = new ArrayList<FalconLangInstruction>(128);
		m_lexicalAnalyzer = new FalconLangLexicalAnalyzer();
		m_syntacticAnalyzer = new FalconLangSyntacticAnalyzer();
		m_translator = new FalconLangTranslator();
	}
	
	public void prepare() {
		m_tokenList.clear();
		m_astList.clear();
		m_lexicalAnalyzer.reset();
		m_syntacticAnalyzer.reset();
		m_translator.reset();
	}
	
	public int analyze(String[] lines) {
		for (int i = 0; i < lines.length; i ++) {
			String line = lines[i];
			int errno = analyze(line);
			if (errno != Errno.SUCCESS) {
				return errno;
			}
		}
		return Errno.SUCCESS;
	}

	public int analyze(String line) {
		int errno = m_lexicalAnalyzer.analyze(line, m_tokenList);
		if (errno != Errno.SUCCESS) {
			return errno;
		}
		if (m_tokenList.isEmpty()) {
			return Errno.SUCCESS;
		}
		errno = m_syntacticAnalyzer.analyze(m_tokenList, m_astList);
		if (errno != Errno.SUCCESS) {
			return errno;
		}
		return Errno.SUCCESS;
	}
	
	public int translate() {
		m_instructionList.clear();
		int errno = m_translator.translate(m_astList, m_instructionList);
		return errno;
	}
	
	public FalconLangInstruction[] getInstruction() {
		FalconLangInstruction[] array = new FalconLangInstruction[0];
		return m_instructionList.toArray(array);
	}

	private ArrayList<FalconLangToken> m_tokenList;
	private ArrayList<FalconLangAst> m_astList;
	private ArrayList<FalconLangInstruction> m_instructionList;
	private FalconLangLexicalAnalyzer m_lexicalAnalyzer;
	private FalconLangSyntacticAnalyzer m_syntacticAnalyzer;
	private FalconLangTranslator m_translator;
}
